package br.com.q7solucoes.parsercinemaq7;

import br.com.q7solucoes.commons.utils.StringUtils;
import br.com.q7solucoes.parsercinemaq7.web.URLReader;
import br.com.q7solucoes.commons.wordpress.WPPost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import sun.net.www.protocol.gopher.GopherClient;

/**
 * Classe que faz o parser de sites para criar posts do Wordpress.
 *
 * @author Elenilson Vieira - elenilson[at]q7solucoes.com.br
 * @since 9 de setembro 2011
 * @version 1.0
 * @see www.q7solucoes.com.br
 */
public class URLParser {

    public static final String GOOGLE_MOVIE_URL = "http://www.google.com.br/movies?near=";
    public static final String BOX_CINEMAS_URL = "http://www.boxcinemas.com.br";
    public static final String MANAIRA_SHOPPING_URL = BOX_CINEMAS_URL + "/complexo_local_prog.asp?id_complexo=15";
    public static final String TAMBIA_SHOPPING_URL = "http://www.shoppingtambia.com.br/cinema.php";
    public static final String MAG_SHOPPING_URL = "http://m.magshopping.com.br/cinema.html";
    public static final String BOULEVARD_SHOPPING_URL = "http://www.boulevardcampina.com.br/site/cinema.php";

    public static final String TAMBIA_SHOPPING_IMAGE_URL = "http://www.lazerjp.com.br/wp-content/uploads/2011/04/multiplex.jpg";
    public static final String MANAIRA_SHOPPING_IMAGE_URL = "http://www.lazerjp.com.br/wp-content/uploads/2011/04/box_cinemas.jpg";
    public static final String MAG_SHOPPING_IMAGE_URL = "http://www.lazerjp.com.br/wp-content/uploads/2011/04/cineespaco.jpg";
    public static final String BOULEVARD_SHOPPING_IMAGE_URL = "http://www.lazercg.com.br/wp-content/uploads/2011/04/sercla.jpg";
    
    public static final String CINEMA_CATEGORY = "cinema";

    public enum URLType{
        GOOGLE_MOVIE, MANAIRA_SHOPPING_CINEMA, TAMBIA_SHOPPING_CINEMA, MAG_SHOPPING_CINEMA, BOULEVARD_SHOPPING_CINEMA
    }

    private URLType uRLType;
    private String url;

    public URLParser(URLType uRLType) {
        this.uRLType = uRLType;
    }
    
    public URLParser(URLType uRLType, String url) {
        this.uRLType = uRLType;
        this.url = url;
    }

    /**
     * Faz o parse da URL para os posts do Wordpress
     *
     * @return a lista de posts
     */
    public WPPost parse() throws IOException{
        WPPost result = null;

        switch(uRLType){
            //case GOOGLE_MOVIE: result = parseGoogleMovie(); break;
            case MANAIRA_SHOPPING_CINEMA: result = parseManairaShopping(); break;
            case TAMBIA_SHOPPING_CINEMA: result = parseTambiaShopping(); break;
            case MAG_SHOPPING_CINEMA: result = parseMagShopping(); break;
            case BOULEVARD_SHOPPING_CINEMA: result = parseBoulevardShopping(); break;
        }

        return result;
    }


//    private WPPost parseGoogleMovie() throws IOException {
//        WPPost new_post = null;
//        /*** Ler a URL. (ajeitar) ***/
//        String content = URLReader.readURL(GOOGLE_MOVIE_URL + url);
//         content = StringUtils.convertToUTF8(content);
//        int vez = 0;
//
//        while(true){
//            // pega o indice de ocorrencia do class = name
//            int indice = content.indexOf("class=name");
//
//            // se nao tiver "class=name"
//            if(indice == -1) break;
//
//            //se tiver excluo os caracteres anteriores a occorrencia
//            content = content.substring(indice);
//
//
//            // a primeira vez eh para pegar o nome do cinema
//
//            if(vez == 0){
//                //procuro o primeiro '>'
//                // pega o indice de ocorrencia do '>'
//                indice = content.indexOf(">");
//                //se tiver excluo os caracteres anteriores a occorrencia
//                content = content.substring(indice);
//
//                String title = "";
//                char c = 'a';
//                int i = 1;
//                while(c != '<'){
//
//                    c = content.charAt(i);
//                    title = title+c;
//                    i++;
//                }
//                vez++;
//
//                title = title.substring(0,title.length()-1);
//                System.out.println("Titulo:" +title);
//                title = StringUtils.convertToUTF8(title);
//
//
//
//                new_post = new WPPost(title, null, null, null, null, null, null);
//            }else{
//
//                // pega o indice da 1 ocorrencia do '>'
//                indice = content.indexOf(">");
//                //se tiver excluo os caracteres anteriores a occorrencia
//                content = content.substring(indice+1);
//
//                // pega o indice da 2 ocorrencia do '>'
//                indice = content.indexOf(">");
//                //se tiver excluo os caracteres anteriores a occorrencia
//                content = content.substring(indice);
//
//
//                String movie_name = "";
//                char c = 'a';
//                int i = 1;
//                while(c != '<'){
//                    c = content.charAt(i);
//                    movie_name = movie_name+c;
//
//                    i++;
//                }
//                vez++;
//
//                movie_name = movie_name.substring(0,movie_name.length()-1);
//                System.out.println("Filme: " +movie_name);
//                movie_name = StringUtils.convertToUTF8(movie_name);
//
//            }
//
//
//
//        }
//
//
//        return new_post;
//    }

    private WPPost parseGoogleMovie() throws IOException {
        String postTitle = null;
        String sinopse = "";
        String horario = "";
        String movie_name = "";
        String movieImageURL = null;
        String classification = null;
        String traillerURL = null;

        StringBuilder contentPost = new StringBuilder();
        List<String> categories = new ArrayList<String>();
        categories.add("Cinema");

        List<String> tags = new ArrayList<String>();
       

        /*** Ler a URL. (ajeitar) ***/
        String content = URLReader.readURL(GOOGLE_MOVIE_URL + url);
         content = StringUtils.removeAccents(content);
        int vez = 0;

         Date date = GregorianCalendar.getInstance().getTime();

        while(true){
            // pega o indice de ocorrencia do class = name
            int indice = content.indexOf("class=name");

            // se nao tiver "class=name"
            if(indice == -1) break;
            //se tiver excluo os caracteres anteriores a occorrencia
            content = content.substring(indice);

            // a primeira vez eh para pegar o nome do cinema

            if(vez == 0){
                //procuro o primeiro '>'
                // pega o indice de ocorrencia do '>'
                indice = content.indexOf(">");
                //se tiver excluo os caracteres anteriores a occorrencia
                content = content.substring(indice);

                postTitle = "";
                char c = 'a';
                int i = 1;
                while(c != '<'){

                    c = content.charAt(i);
                    postTitle = postTitle+c;
                    i++;
                }
                vez++;

                postTitle = postTitle.substring(0,postTitle.length()-1);
                //System.out.println("Cinema:" +postTitle);
                tags.add(postTitle);

                postTitle = StringUtils.removeAccents(postTitle);



            }else{
                // pega o indice da 1 ocorrencia do '>'
                indice = content.indexOf(">");
                //se tiver excluo os caracteres anteriores a occorrencia
                content = content.substring(indice+1);

                // Id do Filme
                String id = "";
                char aux = 'b';
                int indice_aux = 0;

                // pega o indice da 2 ocorrencia do '>'
                indice = content.indexOf(">");

                indice_aux = indice;
                while(aux != '='){
                    aux = content.charAt(indice_aux);
                    id = id + aux;
                    indice_aux--;
                }

                id = id.substring(0, id.length()-1);
                id = new StringBuilder(id).reverse().toString();
                id = id.substring(0, id.length()-2);

                //System.out.println("Id do filme: " + id);
                //se tiver excluo os caracteres anteriores a occorrencia
                content = content.substring(indice);

                // Fim do id do Filme

                // Nome do Filme

                movie_name = "";
                char c = 'a';
                int i = 1;
               
                
                while(c != '<'){
                    c = content.charAt(i);
                    movie_name = movie_name+c;

                    i++;
                }
                vez++;

                movie_name = movie_name.substring(0,movie_name.length()-1);
                movie_name = StringUtils.removeAccents(movie_name);


                //System.out.println("Filme: " + movie_name);
                
                // Fim do nome do filme


                // Classificacao do filme

                // pega o indice da 2 ocorrencia do '>'
                indice = content.indexOf("class=info>");

                classification = "";
                 //se tiver excluo os caracteres anteriores a occorrencia
                content = content.substring(indice+11);

                c = 'a';
                i = 0;
                 while(c != '<'){
                    c = content.charAt(i);
                    classification = classification+c;

                    i++;
                }

                 //System.out.println("CLASSIFICATION:" + classification);

                 classification = StringUtils.removeAccents(classification);

                // Fim da Classificao

                // Horario do Filme
                horario = "Horários(Todos os dias):" ;
                // pega o indice da 2 ocorrencia do '>'
                indice = content.indexOf("class=fl>");
                //se tiver excluo os caracteres anteriores a occorrencia
                content = content.substring(indice+9);

                i = 0;

                int index_prox_movie = content.indexOf("=movie>");
                 String horario_aux = " ";
                try{
                    horario_aux =  content.substring(0, index_prox_movie);
                }catch(Exception e){
                    horario_aux =  content;
                }

               while(indice != -1){
               
                    while (i <= 4){
                        horario += horario_aux.charAt(i);
                        i++;
                    }

                            horario += " - ";
                    
                 // pega o indice da 2 ocorrencia do '>'
                 indice = horario_aux.indexOf("class=fl>");
                 //se tiver excluo os caracteres anteriores a occorrencia
                 horario_aux = horario_aux.substring(indice+9);


                 i = 0;
                }

                //System.out.println("teste: " +horario);

                // Fim do Horario do Filme

                // Sinopse,Horarios e Informacoes
                String info = "";               
                sinopse = "";
                String url2 = null;
                try{
                 url2 = url.substring(0, url.lastIndexOf("tid"));
                }
                catch(Exception e){
                 url2 = url+"&";
                }

                String new_content = URLReader.readURL(GOOGLE_MOVIE_URL +  url2 + "mid="+ id);
                
                // pega o indice da ocorrencia do movie_name
                indice = new_content.lastIndexOf(movie_name);
                 //se tiver excluo os caracteres anteriores a occorrencia
                new_content = new_content.substring(indice+1);

                // pega o indice da ocorrencia do movie_name
                indice = new_content.indexOf("description");
                 //se tiver excluo os caracteres anteriores a occorrencia
                new_content = new_content.substring(indice+12);

               
                char aux_sinopse = 'v';

                i = 1;
                
                while(aux_sinopse != '<'){
                    aux_sinopse = new_content.charAt(i);
                    sinopse += aux_sinopse;
                    i++;
                }
                sinopse = sinopse.substring(0,sinopse.length()-1);
                //System.out.println("Info: "+ sinopse );
            
            }

            List<String> sessionsList = new ArrayList<String>();
            sessionsList.add(horario);
            
            //String movieContent = StringUtils.buildMovieContent(movie_name, movieImageURL, classification, traillerURL, sinopse, sessionsList);
            //contentPost.append(movieContent).append("\n\n");

        }


        return new WPPost(postTitle, contentPost.toString(), GOOGLE_MOVIE_URL, date, categories, tags);
        
    }

    private WPPost parseManairaShopping() throws IOException {
        String postTitle = String.format("Box Cinemas - %s", StringUtils.buildCineDate());
        StringBuilder contentPost = new StringBuilder();
        List<String> categories = new ArrayList<String>();
        categories.add("Cinema");

        List<String> tags = new ArrayList<String>();
        tags.add("Box Cinemas");

        Date date = GregorianCalendar.getInstance().getTime();
        
        /*** Ler a URL***/
        String content = URLReader.readURL(MANAIRA_SHOPPING_URL, "iso-8859-1");

        String contentLines[] = content.split("\n");

        for (int i = 0; i < contentLines.length; i++) {
            String line = contentLines[i];

            /*** Comeca um filme ***/
            if(line.trim().startsWith("<td align=\"center\"><b>Sala")){
                String room = line.replace("<td align=\"center\"><b>", " ").replace("</b></td>", " ").trim();
                
                String movieImageURL = null;
                String language = null;
                String title = null;
                String sinopsis = null;
                String classification = null;
                String traillerURL = null;
                Map<String, List<String>> sessions = new HashMap<String, List<String>>();
                List<String> sessionsOrder = new ArrayList();
                i++;

                while(true){
                    line = contentLines[i];

                    if(line.trim().startsWith("<td rowspan=\"8\"")){
                        /*** Imagem, Nome e Dublado ou Legendado ***/
                        int beginIndex = line.indexOf("<img src=");
                        int endIndex = line.indexOf("\" height=");
                        movieImageURL = line.substring(beginIndex + "<img src=".length() + 1, endIndex);
                        movieImageURL = String.format("%s/%s", BOX_CINEMAS_URL, movieImageURL);
                        
                        line = contentLines[++i];
                        
                        String moreInformationUrl = line.replace("<b><a href=\"javascript:void(0)\" onClick=\"window.open('", " ");
                        moreInformationUrl = moreInformationUrl.replace("', '', 'width=426, height=465, scrollbars=yes');\"><br>", " ").trim();
                        moreInformationUrl = String.format("%s/%s", BOX_CINEMAS_URL, moreInformationUrl);
                        
                        String contentMovie = URLReader.readURL(moreInformationUrl, "iso-8859-1");
                        String contentMovieLines[] = contentMovie.split("\n");
                        
                        for (int j = 0; j < contentMovieLines.length; j++) {
                            if((line = contentMovieLines[j]).contains("Censura")){
                                classification = contentMovieLines[++j].replace("<td>", " ").replace("</td>", " ").trim();
                            }
                            else if((line = contentMovieLines[j]).contains("Sinopse")){
                                sinopsis = contentMovieLines[j].replace("<td><strong>Sinopse:</strong>&nbsp;&nbsp;", " ").replace("</td>", " ").trim();
                                break;
                            }
                        }
                        
                        line = contentLines[++i];
                        language = line.contains("DUB") ? "Dublado" : "Legendado";
                        title = line.replace("</a></b></td>", " ").replace("DUB", " ").replace("LEG", " ").trim();
                        
                        /*** Sessoes ***/
                        i += 2;

                        /*** Pega os dias da sessao ***/
                        while(!(line = contentLines[i]).trim().equals("<td colspan=\"9\"><br><br></td>") && 
                                !contentLines[i].trim().equals("</table>")){
                            if((line = contentLines[i]).contains("table_dia_semana")){
                                String sessionName = contentLines[i++].replace("<td align=\"center\" class=\"table_dia_semana\"><b>", " ").replace("</b></td>", " ").trim();
                            
                                List<String> hours = new ArrayList<String>();
                                while(!contentLines[i].trim().equals("</tr>")){
                                    if((line = contentLines[i]).trim().startsWith("<td align=\"center\" class=\"table_programacao") && 
                                            !contentLines[i].contains(">-<")){
                                        beginIndex = contentLines[i].indexOf("table_programacao") + "table_programacao".length() + 3;
                                        String hour = contentLines[i].substring(beginIndex, contentLines[i].length());
                                        hour = hour.replace("</td>", " ").trim();
                                        
                                        hours.add(hour);
                                    }
                                    
                                    i++;
                                }

                                sessions.put(sessionName, hours);
                                sessionsOrder.add(sessionName);
                            }
                            
                            i++;
                        }
                        
                        break;
                    }

                    i++;
                }

                List<String> sessionsList = new ArrayList<String>();
                for (String sessionDay : sessions.keySet()) {
                    StringBuilder sessionBuilder = new StringBuilder(room);
                    sessionBuilder.append(" (").append(sessionDay).append("): ");

                    boolean first = true;
                    for (String hour : sessions.get(sessionDay)) {
                        if(!first)
                            sessionBuilder.append(" - ");

                        sessionBuilder.append(hour);
                        first = false;
                    }

                    sessionBuilder.append(" (").append(language).append(")");

                    /*** Adiciona a lista ***/
                    sessionsList.add(sessionBuilder.toString());
                }

                String movieContent = StringUtils.buildMovieContent(title, movieImageURL, classification, traillerURL, sinopsis, sessionsList);
                contentPost.append(movieContent).append("\n\n");
            }
        }
        
        return new WPPost(postTitle, contentPost.toString(), postTitle, MANAIRA_SHOPPING_IMAGE_URL, date, categories, tags);
    }

    private WPPost parseMagShopping() throws IOException {
        String postTitle = String.format("Cinespaço - %s", StringUtils.buildCineDate());
        StringBuilder contentPost = new StringBuilder();
        List<String> categories = new ArrayList<String>();
        categories.add("Cinema");
        boolean comment = false;

        List<String> tags = new ArrayList<String>();
        tags.add("Cinespaço");

        Date date = GregorianCalendar.getInstance().getTime();

        /*** Ler a URL***/
        String content = URLReader.readURL(MAG_SHOPPING_URL, "iso-8859-1");

        String contentLines[] = content.split("\n");

        for (int i = 0; i < contentLines.length; i++) {
            String line = contentLines[i];

            if(line.contains("<!--")){
                comment = true;
            }
            else if(line.contains("-->")){
                comment = false;
            }
            else if(!comment && line.trim().startsWith("<li class=\"")){
                /*** E' um filme ***/
                i += 2;
                line = contentLines[i];
                
                String title = line.replace("<h2>", " ").replace("</h2>", " ").trim();
                String movieImageURL = null;
                String sinopsis = null;
                String classification = null;
                String traillerURL = null;
                List<String> sessionsList = new ArrayList<String>();

                out : while(true){
                    line = contentLines[++i];

                    if(line.trim().startsWith("<img src=\"")){
                        /*** Imagem ***/
                        String beginImage = "<img src=\"";
                        movieImageURL = line.substring(line.indexOf(beginImage) + beginImage.length());
                        movieImageURL = movieImageURL.substring(0, movieImageURL.indexOf(".png") + 4).trim();
                    }else if(line.trim().startsWith("<br><br>")){
                        /*** Sessoes e Sala ***/
                        line = contentLines[++i];
                        line = line.substring(0, line.lastIndexOf("&nbsp;")).trim();

                        sessionsList.add(line);
                    }else if(line.trim().startsWith("<div class=\"btnMore2\">")){
                        /*** Sinopse ***/
                        String endSinopse = "\" title=\"";
                        String urlPageSinopsis = line.replace("<div class=\"btnMore2\"><a href=\"", " ").trim();
                        urlPageSinopsis = urlPageSinopsis.substring(0, urlPageSinopsis.lastIndexOf(endSinopse));
                        String contentPageSinopsis = URLReader.readURL(urlPageSinopsis, "iso-8859-1");

                        String contentPageSinopsisLine[] = contentPageSinopsis.split("\n");
                        for (int j= 0; j < contentPageSinopsisLine.length; j++) {
                            line = contentPageSinopsisLine[j];

                            if(line.trim().startsWith("<div id=\"sinopse\"")){
                                sinopsis = contentPageSinopsisLine[++j].trim();
                                break out;
                            }
                        }
                    }

                }

                String movieContent = StringUtils.buildMovieContent(title, movieImageURL, classification, traillerURL, sinopsis, sessionsList);
                contentPost.append(movieContent).append("\n\n");
            }
        }

        return new WPPost(postTitle, contentPost.toString(), postTitle, MAG_SHOPPING_IMAGE_URL, date, categories, tags);
    }

   private WPPost parseBoulevardShopping() throws IOException {
        String postTitle = String.format("CineSercla Boulevard - %s", StringUtils.buildCineDate());
        StringBuilder contentPost = new StringBuilder();
        List<String> categories = new ArrayList<String>();
        categories.add("Cinema");

        List<String> tags = new ArrayList<String>();
        tags.add("CineSercla");

        Date date = GregorianCalendar.getInstance().getTime();

        /*** Ler a URL***/
        String content = URLReader.readURL(BOULEVARD_SHOPPING_URL, "iso-8859-1");

        String contentLines[] = content.split("\n");

        for (int i = 0; i < contentLines.length; i++) {
            String line = contentLines[i];

            /*** Comeca um filme ***/
            if(line.trim().startsWith("<td class=\"Figura2\"><table width=\"116\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">")){
                String title = null;
                String movieImageURL = null;
                String room = null;
                String language = null;
                String sinopsis = null;
                String classification = null;
                String traillerURL = null;
                List<String> sessionsList = new ArrayList<String>();

                while(true){
                    line = contentLines[++i];
                    
                    if(line.trim().startsWith("<td height=\"120\" class=\"Figura4\"><div align=\"center\"><img src=\"")){
                        /*** Imagem ***/
                        movieImageURL = line.replace("<td height=\"120\" class=\"Figura4\"><div align=\"center\"><img src=\"", " ")
                                .replace("\" alt=\"\" width=\"100\"/></div></td>", " ").trim();

                        movieImageURL = BOULEVARD_SHOPPING_URL.replace("cinema.php", " ").trim() + movieImageURL;
                    }
                    else if(line.trim().startsWith("<td class=\"cinema_titulo\">")){
                        /*** Titulo ***/
                        title = line.replace("<td class=\"cinema_titulo\"><div align=\"left\">", " ").replace("</div></td>", " ").trim();
                    }
                    else if(line.trim().startsWith("<td height=\"50\" valign=\"top\" class=\"cinema_texto\"><div align=\"justify\"><p>")){
                        /*** Sinopse ***/
                        line = contentLines[++i];
                        sinopsis = line.replace("</p>", " ").trim();
                    }
                    else if(line.trim().startsWith("<td class=\"cinema_texto\"><div align=\"left\"><strong>Censura:</strong>")){
                        /*** Censura ***/
                        classification = line.replace("<td class=\"cinema_texto\"><div align=\"left\"><strong>Censura:</strong>", " ")
                                .replace("<div align=\"left\"></div></td>", " ").replace("</div>", " ").trim();
                    }
                    else if(line.trim().startsWith("<td class=\"cinema_texto\"><strong>Observação:</strong> <p>")){
                        /*** Dublado/Legendado ***/
                        line = contentLines[++i];
                        language = line.replace(".</p>", " ").replace("</p>", " ").trim();
                    }
                    else if(line.trim().startsWith("<td height=\"50\" valign=\"top\" class=\"cinema_texto\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">")){
                        /*** Sala ***/
                        i += 2;
                        line = contentLines[i];
                        room = line.replace("<td height=\"25\" class=\"cinema_texto\"><strong>Sala:</strong>", " ")
                                .replace("</td>", " ").trim();

                        /*** Horarios ***/
                        i += 3;
                        line = contentLines[i];
                        String sessions = line.replace("<td height=\"25\" class=\"cinema_texto\"><strong>Horários:</strong>", " ")
                                .replace("</td>", " ").trim();
                        sessions = String.format("Sala %s (todos os dias): %s (%s)", room, sessions, language);
                        sessionsList.add(sessions);

                        /*** pegou tudo ***/
                        break;
                    }

                }

                String movieContent = StringUtils.buildMovieContent(title, movieImageURL, classification, traillerURL, sinopsis, sessionsList);
                contentPost.append(movieContent).append("\n\n");
            }
        }

        return new WPPost(postTitle, contentPost.toString(), postTitle, BOULEVARD_SHOPPING_IMAGE_URL, date, categories, tags);
    }

    
   private WPPost parseTambiaShopping() throws IOException {
        String postTitle = String.format("Cine Multiplex - %s", StringUtils.buildCineDate());
        StringBuilder contentPost = new StringBuilder();
        List<String> categories = new ArrayList<String>();
        categories.add("Cinema");
        
        List<String> tags = new ArrayList<String>();
        tags.add("Cine Multiplex");
        
        Date date = GregorianCalendar.getInstance().getTime();
        
        
        /*** Ler a URL. (ajeitar) ***/
        String content = URLReader.readURL(TAMBIA_SHOPPING_URL, "iso-8859-1");
        
        //System.out.println("1>>>>>>>>>>>>\n" + content);
        
        String contentLines[] = content.split("\n");
        
        String temp1[], temp2[];
        
        int count = 0;
        for (int i = 0; i < contentLines.length; i++){
            String line = contentLines[i];
            
            // Aqui a string que inicia cada filme.
            if(line.trim().startsWith("<div id=\"filme\" class=\"clear\">") || line.trim().startsWith("</div><div id=\"filme\" class=\"clear\">")){
                
                //pega a próxima linha que é a do filme;
                i++;
                line = contentLines[i];
                temp1 = line.split(">");
                //System.out.println("2>>>>>>>>>>> Line: " + line);
                String imagemDoFilme = TAMBIA_SHOPPING_URL.replace("cinema.php", "");
                String urlDoFilme = TAMBIA_SHOPPING_URL.replace("cinema.php", "");
                
                //Pega a url do filme e a url da imagem do filme.
                for (int k = 0; k < temp1.length; k++) {
                    if(temp1[k].trim().contains("<a href=\"cinema_detalhes.php?id=")){
                        urlDoFilme += temp1[k].trim().replace("<a href=\"", "");
                        urlDoFilme = urlDoFilme.trim().replace("\"", "");
                        //System.out.println("urlDoFilme = " + urlDoFilme);
                    }
                    
                    if(temp1[k].trim().contains("<img src=\"")){
                        temp1[k] = temp1[k].trim().replace("<img src=\"", "");
                        temp1[k] = temp1[k].trim().replace("\" alt=\"\" /", "");
                        imagemDoFilme += temp1[k];
                        //System.out.println("imagemDoFilme = " + imagemDoFilme);
                    }
                }
                
                
                String movieContent = getFilmeTambia(urlDoFilme, imagemDoFilme);
            }
        }
        //System.out.println("1>>>>>>>>>>>>\n" + content);
        
        String linesContent[] = content.split("\n");
        
        String temp[], aux[];
        
        int contador = 0;
        
        for (int i = 0; i < linesContent.length; i++){
            String line = linesContent[i];
            
            // Aqui a string que inicia cada filme.
            if(line.trim().startsWith("<div id=\"filme\" class=\"clear\">") || line.trim().startsWith("</div><div id=\"filme\" class=\"clear\">")){
                
                //pega a próxima linha que é a do filme;
                i++;
                line = linesContent[i];
                temp = line.split(">");
                //System.out.println("2>>>>>>>>>>> Line: " + line);
                String imagemDoFilme = TAMBIA_SHOPPING_URL.replace("cinema.php", "");
                String urlDoFilme = TAMBIA_SHOPPING_URL.replace("cinema.php", "");
                
                //Pega a url do filme e a url da imagem do filme.
                for (int k = 0; k < temp.length; k++) {
                    if(temp[k].trim().contains("<a href=\"cinema_detalhes.php?id=")){
                        urlDoFilme += temp[k].trim().replace("<a href=\"", "");
                        urlDoFilme = urlDoFilme.trim().replace("\"", "");
                        //System.out.println("urlDoFilme = " + urlDoFilme);
                    }
                    
                    if(temp[k].trim().contains("<img src=\"")){
                        temp[k] = temp[k].trim().replace("<img src=\"", "");
                        temp[k] = temp[k].trim().replace("\" alt=\"\" /", "");
                        imagemDoFilme += temp[k];
                        //System.out.println("imagemDoFilme = " + imagemDoFilme);
                    }
                }
                
                
                String movieContent = getFilmeTambia(urlDoFilme, imagemDoFilme);
                contentPost.append(movieContent).append("\n\n");
            }
        }
        
        return new WPPost(postTitle, contentPost.toString(), TAMBIA_SHOPPING_IMAGE_URL,  date, categories, tags);
    }

//    private String getFilmeTambia(String urlDoFilme, String urlDaImagem) throws IOException{
//        String filme = URLReader.readURL(urlDoFilme);
//        String linhasDoFilme[] = filme.split("\n");
//        String nomeDoFilme = "", sala, sinopse = "";
//        ArrayList<String> horarios = new ArrayList<String>();
//        String temp[];
//        String trailer = "trailer.php?id=";
//        String classificacao[];
//        String classif = null;
//        
//        for (int i = 0; i < linhasDoFilme.length; i++) {
//            //Pega o nome do filme.
//            if(linhasDoFilme[i].trim().contains("<h3>")){
//                nomeDoFilme = linhasDoFilme[i].trim().replace("<h3>", "");
//                nomeDoFilme = nomeDoFilme.trim().replace("</h3><br />", "");
//                
//                System.out.println("Nome do Filme = " + nomeDoFilme);
//            }
//            
//            //Pega a sala.
//            if(linhasDoFilme[i].trim().contains("<p><strong>Sala:</strong>")){
//                sala = linhasDoFilme[i].trim().replace("<p><strong>Sala:</strong>", "");
//                sala = sala.trim().replace("</p><br />", "");
//                
//                System.out.println("Sala: " + sala);
//            }
//            //Pega os Horários
//            if(linhasDoFilme[i].trim().contains("Sab") && linhasDoFilme[i].trim().contains("Dom")){
//                temp = linhasDoFilme[i].trim().split("<td class='center'>");
//                
//                for (int k = 0; k < temp.length; k++) {
//                    if(temp[k].trim().contains("Sab")){
//                        k++;
//                        for (int j = k; j < (k+6); j++) {
//                            if(temp[j].trim().contains("h</td>")){
//                                horarios.add(temp[j].trim().replace("</td>", ""));
//                            }
//                        }
//                    }
//                }
//                System.out.println("Horários: " + horarios);
//            }
//            //Pega a Sinopse
//            if(linhasDoFilme[i].trim().contains("Sinopse")){
//                i++;
//                sinopse = linhasDoFilme[i].trim().replace("</p></p><p>", "");
//                System.out.println("Sinopse = " + sinopse);
//            }
//            
//            if(linhasDoFilme[i].trim().contains("Classif")){
//                System.out.println("Classificação: " + linhasDoFilme[i]);
//                i++;
//                
//                classificacao = linhasDoFilme[i].trim().split("</span><br");
//                
//                for (int k = 0; k < classificacao.length; k++) {
//                    if(classificacao[k].trim().contains("Anos")){
//                        classif = classificacao[k].substring(classificacao[k].indexOf("Anos") - 3);
//                        System.out.println("Classificação: " + classif);
//                    }            
//                }
//                if(classif == null)
//                    classif = "Livre";
//            }
//        }
//        
//        //Pega o Trailer
//        trailer = "http://www.shoppingtambia.com.br/trailer.php?";
//        trailer += urlDoFilme.trim().substring(urlDoFilme.indexOf("id="));
//        System.out.println("Trailer = " + trailer);
//        
//        //String movieContent = 
//        return StringUtils.buildMovieContent(nomeDoFilme, urlDoFilme, classif, trailer, sinopse, horarios);
//    }
    
    
    private String getFilmeTambia(String urlDoFilme, String urlDaImagem) throws IOException{
        String filme = URLReader.readURL(urlDoFilme, "iso-8859-1");
        String linhasDoFilme[] = filme.split("\n");
        String nomeDoFilme = "", sala = "", sinopse = "";
        ArrayList<String> horarios = new ArrayList<String>();
        StringBuilder horariosBuilder;
        String temp[];
        String trailer = "trailer.php?id=";
        String classificacao[];
        String classif = null;
        String audio = "";
        for (int i = 0; i < linhasDoFilme.length; i++) {
            //Pega o nome do filme.
            if(linhasDoFilme[i].trim().contains("<h3>")){
                nomeDoFilme = linhasDoFilme[i].trim().replace("<h3>", "");
                nomeDoFilme = nomeDoFilme.trim().replace("</h3><br />", "");
                
                if(nomeDoFilme.contains("dublado") || nomeDoFilme.contains("Dublado")){
                    audio = "Dublado";
                }
                else{
                    audio = "Legendado";
                }
                //System.out.println("Nome do Filme = " + nomeDoFilme);
            }
            
            //Pega a sala.
            if(linhasDoFilme[i].trim().contains("<p><strong>Sala:</strong>")){
                sala = linhasDoFilme[i].trim().replace("<p><strong>Sala:</strong>", "");
                sala = sala.trim().replace("</p><br />", "");
                
                //System.out.println("Sala: " + sala);
            }
            //Pega os Horários
            if(linhasDoFilme[i].trim().contains("Sab") && linhasDoFilme[i].trim().contains("Dom")){
                temp = linhasDoFilme[i].trim().split("<td class='center'>");
                
                horariosBuilder = new StringBuilder("Sala " + sala + "(Todos os dias): ");
                
                for (int k = 0; k < temp.length; k++) {
                    if(temp[k].trim().contains("Sab")){
                        k++;
                        for (int j = k; j < (k+6); j++) {
                            if(temp[j].trim().contains("h</td>")){
                                //horarios.add(temp[j].trim().replace("</td>", ""));
                                horariosBuilder.append(temp[j].trim().replace("</td>", "")).append(" ");
                                if(j < k+4){
                                    horariosBuilder.append(" - ");
                                }
                            }
                        }
                    }
                }
                //System.out.println("Horários: " + horarios);
                
                horarios.add(horariosBuilder.toString() + " (" + audio + ")" );
            }
            //Pega a Sinopse
            if(linhasDoFilme[i].trim().contains("Sinopse")){
                i++;
                sinopse = linhasDoFilme[i].trim().replace("</p></p><p>", "");
                //System.out.println("Sinopse = " + sinopse);
            }
            
            if(linhasDoFilme[i].trim().contains("Classif")){
                //System.out.println("Classificação: " + linhasDoFilme[i]);
                i++;
                
                classificacao = linhasDoFilme[i].trim().split("</span><br");
                
                for (int k = 0; k < classificacao.length; k++) {
                    if(classificacao[k].trim().contains("Anos")){
                        classif = classificacao[k].substring(classificacao[k].indexOf("Anos") - 3);
                       // System.out.println("Classificação: " + classif);
                    }            
                }
                if(classif == null)
                    classif = "Livre";
            }
        }
        
        //Pega o Trailer
        trailer = "http://www.shoppingtambia.com.br/trailer.php?";
        trailer += urlDoFilme.trim().substring(urlDoFilme.indexOf("id="));
        //System.out.println("Trailer = " + trailer);
        
        //String movieContent = 
        return StringUtils.buildMovieContent(nomeDoFilme, urlDaImagem, classif, trailer, sinopse, horarios);
    }
    
}
